package com.lancoo.answer.view.fragment.composition.answer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.ivan.easycamera.util.FileUtil;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.ConfirmDialogHelper;
import com.lancoo.answer.helper.LoadDialogHelper;
import com.lancoo.answer.manager.MediaManager;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.AudioUpLoadCallBackEventBean;
import com.lancoo.answer.model.eventBean.AudioUpLoadEventBean;
import com.lancoo.answer.util.EditTextInputUtil;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.NetWorkTools;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.WavAppendUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.lancoo.answer.widget.WaveView;
import com.rxjava.rxlife.RxLife;
import com.stkouyu.LancooSpeechRecognitionManager;
import com.stkouyu.listener.OnLancooSpeechRecognitionListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/8 14:15
 * Description:
 */
public class CompositionAudioAnswerFragment extends Fragment implements View.OnClickListener,View.OnTouchListener{

    private View convertView;
    private Item item;
    private long subTime;
    private static final String TAG = "CompositionAudioAnswerF";
    private WaveView waveView;
    private PopupWindow popupWindow;
    private MediaManager mediaManager;
    private int typeIndex;
    private int quesIndex;
    private int childIndex;
    private int itemIndex;
    private AlertDialog loadDialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        convertView =inflater.inflate(R.layout.ev_fragment_composition_answer_type_audio,container,false);
        return convertView;
    }


    public static Fragment loadFragment(int kindIndex, int queseIndex, int smallQueseIndex,int itemIndex){

        CompositionAudioAnswerFragment fragment=new CompositionAudioAnswerFragment();
        Bundle mBundle=new Bundle();
        mBundle.putInt("kindIndex",kindIndex);
        mBundle.putInt("queseIndex",queseIndex);
        mBundle.putInt("smallQueseIndex",smallQueseIndex);
        mBundle.putInt("itemIndex",itemIndex);
        fragment.setArguments(mBundle);
        return fragment;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        adjustFontSize();
    }


    private void initView(View view){
        if(getArguments()==null){
            return;
        }
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        typeIndex = getArguments().getInt("kindIndex");
        quesIndex = getArguments().getInt("queseIndex");
        childIndex = getArguments().getInt("smallQueseIndex");
        itemIndex = getArguments().getInt("itemIndex");
        if( ConstantBean.Companion.getConstantExamBean()==null){
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if(kindBeanListk==null){
            return;
        }
        item = kindBeanListk.get(typeIndex).getQuesList().get(quesIndex)
                .getChildList().get(childIndex).getItemList().get(itemIndex);
        EditText editText = view.findViewById(R.id.edittext);

        editText.setText(getStuAnswerStr());
        if(editText.getText()!=null&&editText.getText().length()>0){
            editText.setSelection(editText.getText().length());
        }
        SoftInputUtils.setEditTextInputSpace(editText);
        EditTextInputUtil.disableCopyAndPaste(editText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                setStuAnswerStr(editable.toString().trim());
                updateAnswerCount();
            }
        });
        updateAnswerCount();
        view.findViewById(R.id.tv_clear_answer).setOnClickListener(this);
        view.findViewById(R.id.tv_my_audio).setOnClickListener(this);
        view.findViewById(R.id.img_microphone_recording).setOnTouchListener(this);
        updateMyAudioStyle();
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean!=null&&taskControlBean.getEnableAnwer()==0){//禁止作答
            view.findViewById(R.id.edittext).setEnabled(false);
            view.findViewById(R.id.tv_clear_answer).setEnabled(false);
            view.findViewById(R.id.tv_my_audio).setEnabled(false);
            view.findViewById(R.id.img_microphone_recording).setEnabled(false);
        }
        if(taskControlBean!=null&&taskControlBean.isCloseMediaAnswer()){
            view.findViewById(R.id.rl_bottom).setVisibility(View.GONE);
        }

    }

    /**
     * 统计作答个数
     */
    private void updateAnswerCount(){
        TextView tv_answerCount= convertView.findViewById(R.id.tv_answer_count);

        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    int count=0;
                    if(!TextUtils.isEmpty(getStuAnswerStr())){
                        String[] split = getStuAnswerStr()
                                .replace("\n"," ")
                                .split(" ");
                        count=split.length;
                        for (String str : split) {
                            if (str.isEmpty()) {
                                count--;
                            }
                        }
                    }
                    emitter.onNext(Math.max(count,0));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(integer -> {

                    SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                    spannableStringBuilder.append("Word Count:");
                    SpannableString spannableString=new SpannableString(""+integer);
                    spannableString.setSpan(new ForegroundColorSpan(0xff666666),0,spannableString.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    tv_answerCount.setText(spannableStringBuilder);
                }, throwable -> {});

    }

    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-subTime<500){
            return;
        }
        subTime=System.currentTimeMillis();
        int id = v.getId();
        if(id==R.id.tv_clear_answer){
            showSwitchAnswerTypeDialog();
        }else if(id==R.id.tv_my_audio){
            if(mediaManager==null||!mediaManager.isPlay()){
                startPlayRecordSound();
                showPlayState(true);
            }else{
                showPlayState(false);
                mediaManager.pause();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        release();
        EventBus.getDefault().unregister(this);
    }

    private void showSwitchAnswerTypeDialog(){
        if(getContext()==null){
            return;
        }
        View inflate=LayoutInflater.from(getContext()).inflate(R.layout.ev_dialog_switch_answer_type,null);
        AlertDialog.Builder builder=new AlertDialog.Builder(getContext(),R.style.ev_dialogStyle);
        builder.setView(inflate);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        if(window==null){
            return;
        }
        WindowManager.LayoutParams attributes = window.getAttributes();
        int width = getContext().getResources().getDisplayMetrics().widthPixels;
        int px280 = (int)getContext().getResources().getDisplayMetrics().density*280;
        attributes.width=Math.min(width*280/375,px280);
        alertDialog.getWindow().setAttributes(attributes);
        TextView tv_content=inflate.findViewById(R.id.tv_content);
        tv_content.setText("您确认清空录音吗？");
        TextView tv_cancel=inflate.findViewById(R.id.tv_cancel);
        tv_cancel.setText("取消");
        inflate.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            if(System.currentTimeMillis()-subTime<200){
                return;
            }
            subTime=System.currentTimeMillis();
            alertDialog.dismiss();
        });
        inflate.findViewById(R.id.tv_sure).setOnClickListener(v -> {
            if(System.currentTimeMillis()-subTime<200){
                return;
            }
            subTime=System.currentTimeMillis();
            alertDialog.dismiss();
            try{
                FileUtil.deleteFile(item.getAudioLocalPath());
            }catch (Exception e){
                e.printStackTrace();
            }
            AudioUpLoadEventBean audioUpLoadEventBean=new AudioUpLoadEventBean();
            audioUpLoadEventBean.setTypeIndex(typeIndex);
            audioUpLoadEventBean.setQueseIndex(quesIndex);
            audioUpLoadEventBean.setChildIndex(childIndex);
            audioUpLoadEventBean.setAudioLocalPath(item.getAudioPath());
            audioUpLoadEventBean.setOperateType(1);
            EventBus.getDefault().post(audioUpLoadEventBean);
            item.setAudioPath("");
            item.setAudioLocalPath("");
//            editText.setText("");
            pause();
            updateMyAudioStyle();
            if(mediaManager!=null){
                mediaManager.stop();
            }

            Log.e("eee","delet:"+new Gson().toJson(audioUpLoadEventBean));
        });
    }



    private void updateMyAudioStyle(){
        TextView tv_myAudio = convertView.findViewById(R.id.tv_my_audio);
        View view_end = convertView.findViewById(R.id.view_end);
        TextView tv_clearAnswer = convertView.findViewById(R.id.tv_clear_answer);
        View view_start = convertView.findViewById(R.id.view_start);
        if(TextUtils.isEmpty(item.getAudioPath())){
            tv_myAudio.setEnabled(false);
            tv_myAudio.setTextColor(0xff999999);
            tv_myAudio.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_horn_gray,0,0,0);
            view_end.setBackgroundResource(R.drawable.ev_shape_audio_answer_f7_bg);

            tv_clearAnswer.setEnabled(false);
            tv_clearAnswer.setTextColor(0xff999999);
            tv_clearAnswer.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_delet_answer_gray,0,0,0);
            view_start.setBackgroundResource(R.drawable.ev_shape_audio_answer_f7_bg);
        }else{
            tv_myAudio.setEnabled(true);
            tv_myAudio.setTextColor(0xff0099ff);
            tv_myAudio.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_horn_1,0,0,0);
            view_end.setBackgroundResource(R.drawable.ev_shape_audio_answer_bg);
            tv_clearAnswer.setEnabled(true);
            tv_clearAnswer.setTextColor(0xff0099ff);
            tv_clearAnswer.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_delet_answer,0,0,0);
            view_start.setBackgroundResource(R.drawable.ev_shape_audio_answer_bg);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                subTime= System.currentTimeMillis();
                startRecognition();
                v.getParent().requestDisallowInterceptTouchEvent(true);
                FragmentCommunicationUtils.testEventBus();
                return true;
            case MotionEvent.ACTION_UP:
                if(NetWorkTools.isNetworkConnected(getContext())){
                    boolean isResult= System.currentTimeMillis()-subTime>=200;
                    stopRecognition(isResult);
                }else{
                    stopRecognition(false);
                    Toast.makeText(getContext(),"抱歉，当前网络不可用", Toast.LENGTH_SHORT).show();
                }
                return true;
            case MotionEvent.ACTION_CANCEL:
//                stopRecognition(false);
                return true;
        }
        return false;
    }


    private void startRecognition(){
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
//            Toast.makeText(getApplicationContext(), "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            String[] pressisionArray;
            try {
                pressisionArray = new String[]{Manifest.permission.RECORD_AUDIO};
                Log.e("eeee", "权限不足，请求响应");
                ActivityCompat.requestPermissions( getActivity(), pressisionArray, 100);//,Manifest.permission.READ_PHONE_STATE
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("eeee", "权限不足，error:"+e.toString());
            }
            return;
        }
        pause();
        showRecordPop();
        LancooSpeechRecognitionManager.getInstance(getContext())
                .startSpeechRecognition(0, new OnLancooSpeechRecognitionListener() {
                    @Override
                    public void onSpeechRecognitionStart() {

                    }

                    @Override
                    public void onSpeechRecogniting(int vad_status, int sound_intensity) {

                        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                                    emitter.onNext(sound_intensity);
                                })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .as(RxLife.as(CompositionAudioAnswerFragment.this))
                                .subscribe(o -> {
                                    if(waveView!=null){
                                        waveView.setVisibility(View.VISIBLE);
                                        waveView.addData((short)sound_intensity);
                                    }
                                }, throwable -> {});
                    }

                    @Override
                    public void onSpeechRecognitionEnd(String recognitionSentence, String url) {
                        appeandAudioFile(recognitionSentence,url);
                    }

                    @Override
                    public void onSpeechRecognitionError(String error) {

                    }
                });
    }


    private void stopRecognition(boolean isEnd){
        LancooSpeechRecognitionManager.getInstance(getContext()).stopSpeechRecognition(isEnd);
        if(popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
        }
    }





    /**
     * 上传本地音频
     */
    private void startUpLoadAudio(String tempUrl){
        Log.e(TAG,"kindIndex:"+ typeIndex);
        Log.e(TAG,"queseIndex:"+ quesIndex);
        Log.e(TAG,"smallQueseIndex:"+ childIndex);
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        int mediaAnswerSaveType = taskControlBean.getMediaAnswerSaveType();
        AudioUpLoadEventBean audioUpLoadEventBean=new AudioUpLoadEventBean();
        audioUpLoadEventBean.setTypeIndex(typeIndex);
        audioUpLoadEventBean.setQueseIndex(quesIndex);
        audioUpLoadEventBean.setChildIndex(childIndex);
        audioUpLoadEventBean.setAudioLocalPath(tempUrl);
        EventBus.getDefault().post(audioUpLoadEventBean);
        if(mediaAnswerSaveType==0){

            item.setAudioPath(tempUrl);
            item.setAudioDuration(0L);
            Log.e(TAG,"next");
            appendAnswer(appendContent,tempUrl);
            return;
        }
        if(getContext()==null){
            return;
        }
        loadDialog =LoadDialogHelper.showLoadDialog(getContext(), R.string.ev_uploading,false);
    }

    private void showRecordPop(){
        View inflater= LayoutInflater.from(getContext()).inflate(R.layout.ev_layout_pop_recording,null);
        popupWindow = new PopupWindow(inflater,
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.showAtLocation(convertView, Gravity.CENTER,0,0);
        waveView = inflater.findViewById(R.id.waveview);
    }

    public void pause(){
        Log.e(TAG,"pause");
        if(mediaManager!=null){
            mediaManager.pause();
        }
        showPlayState(false);
    }

    public void release(){
        if(mediaManager!=null){
            mediaManager.release();
        }
    }


    private void startPlayRecordSound(){
        if(getContext()==null){
            return;
        }
        if(mediaManager==null){
            mediaManager=new MediaManager(getContext());
        }

        String url = item.getAudioPath();
        if(mediaManager.isPrepared()){
            mediaManager.start();
            return;
        }
        mediaManager.setUpMedia(url, new MediaManager.OnPlayListener() {
            @Override
            public void onComplete() {
                showPlayState(false);
            }

            @Override
            public void onStartError() {
                showPlayState(false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                showPlayState(false);
            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                if(mediaManager!=null){
                    mediaManager.start();
                }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.e(TAG,"onBufferingUpdate:"+percent);
            }
        });
    }

    private int times=0;
    private Disposable mDisposable;
    private void showPlayState(boolean isPlaying){
        if( Looper.myLooper() != Looper.getMainLooper()){
            return;
        }
        if(convertView ==null){
            return;
        }
        TextView tv_myAudio = convertView.findViewById(R.id.tv_my_audio);
        if(tv_myAudio!=null&&tv_myAudio.isEnabled()){
            if(isPlaying){
                if(mDisposable!=null){
                    mDisposable.dispose();
                }
                times=0;
                Observable.interval(500, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .as(RxLife.as(this))
                        .subscribeWith(new Observer<Long>() {

                            @Override
                            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable disposable) {
                                mDisposable = disposable;
                            }

                            @Override
                            public void onNext(@io.reactivex.annotations.NonNull Long number) {
                                times++;
                                switch (times%3){
                                    case 1:
                                        tv_myAudio.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_horn_0,0,0,0);

                                        break;
                                    case 2:
                                        tv_myAudio.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_horn_1,0,0,0);
                                        break;
                                    default:
                                        tv_myAudio.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_horn_2,0,0,0);
                                }
                            }

                            @Override

                            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

                            }

                            @Override

                            public void onComplete() {
                            }

                        });
            }else{
                if (mDisposable != null){
                    mDisposable.dispose();
                }
                tv_myAudio.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ev_vector_horn_0,0,0,0);
            }
        }else{
            updateMyAudioStyle();
        }
    }

    /**
     * 音频上传
     */
    //
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAudioUpLoadCallBackEvent(final AudioUpLoadCallBackEventBean callBackEventBean) {
        Log.e(TAG,"音频上传上传执行结果回调\n"+new Gson().toJson(callBackEventBean));
        Log.e(TAG,"kindIndex:"+ typeIndex);
        Log.e(TAG,"queseIndex:"+ quesIndex);
        Log.e(TAG,"smallQueseIndex:"+ childIndex);

        if(callBackEventBean.getTypeIndex()== typeIndex &&
                callBackEventBean.getQueseIndex()== quesIndex &&
                callBackEventBean.getChildIndex()== childIndex &&
                callBackEventBean.getItemIndex()== itemIndex){
            Log.e(TAG,"进来了");
            String url=callBackEventBean.getAudioPath();
            if(loadDialog!=null&&loadDialog.isShowing()){
                loadDialog.dismiss();
                Log.e(TAG," loadDialog.dismiss()");
            }
            if(!TextUtils.isEmpty(url)&&callBackEventBean.isSuccess()){
                item.setAudioPath(url);
                item.setAudioDuration(callBackEventBean.getAudioDuration());
                Log.e(TAG,"next");
                appendAnswer(appendContent,tempUrl);
            }else{

                if(getContext()!=null){
                    showAudioUploadFailureDialog();
                }

            }
        }
    }


    private String appendContent;
    private String tempUrl;

    /**
     * 音频识别成功后，先拼接，再上传，再回显
     * @param appendContent content
     * @param tempUrl url
     */
    private void appeandAudioFile(String appendContent,String tempUrl){
        this.appendContent=appendContent;
        this.tempUrl=tempUrl;
        if(TextUtils.isEmpty(item.getAudioLocalPath())){//如果本地存储的文件为空，就直接上传录音文件
            startUpLoadAudio(tempUrl);
        }else{
            Log.e(TAG,"本地音频不为空，需特殊处理"+tempUrl);

            Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
                        String tempPath=System.currentTimeMillis()+".wav";
                        String tempRecordFilePath = getTempRecordFilePath();
                        File newFile=new File(tempRecordFilePath,tempPath);//newFile是新的temp文件，用于上传时的临时文件
                        if(!newFile.exists()){
                            boolean newFile1 = newFile.createNewFile();
                            Log.e(TAG,"下一步进行临时文件拷贝"+newFile1);
                        }
                        Log.e(TAG,"下一步进行临时文件拷贝");
                        //把已保存的本地录音音频copy到temp文件中进行合成，再上传
                        FileInputStream fileInputStream=new FileInputStream(item.getAudioLocalPath());
                        FileOutputStream fileOutputStream=new FileOutputStream(newFile);
                        byte[] buffer=new byte[1024];
                        int byteRead;
                        while (-1!=(byteRead =fileInputStream.read(buffer))){
                            fileOutputStream.write(buffer,0,byteRead);
                        }
                        fileInputStream.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();

                        File oldFile=new File(newFile.getPath());
                        File mergeFile=new File(tempUrl);
                        boolean isSuccess=WavAppendUtils.appendWav(oldFile,mergeFile);
                        if(isSuccess){
                            CompositionAudioAnswerFragment.this.tempUrl=newFile.getPath();
                        }
                        emitter.onNext(isSuccess);
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(RxLife.as(this))
                    .subscribe(aBoolean -> {
                        if(aBoolean){
                            if(mediaManager!=null){
                                mediaManager.stop();
                            }
                            startUpLoadAudio(CompositionAudioAnswerFragment.this.tempUrl);
                        }
                        Log.e(TAG,"isSuccess"+aBoolean);
                    }, throwable -> {});
        }
    }


    private void appendAnswer(String appendContent,final String url){
        if(!TextUtils.isEmpty(appendContent)){
            boolean isEndEmpty=appendContent.endsWith(" ");
            String substring = appendContent.substring(0, 1);
            String s = substring.toUpperCase();
            appendContent=s+appendContent.substring(1,appendContent.length()-(isEndEmpty?1:0))+".";
        }
        Log.e(TAG,"appendAnswer:"+appendContent);
        EditText edittext = convertView.findViewById(R.id.edittext);
        Editable text = edittext.getText();
        if(TextUtils.isEmpty(text)){
            edittext.setText(appendContent);
            edittext.setSelection(edittext.getText().length());
        }else{
            int selectionStart = edittext.getSelectionStart();
            if(selectionStart>=0&&selectionStart<text.length()){
                text.insert(selectionStart,appendContent);
                edittext.setText(text);
                edittext.setSelection(selectionStart+appendContent.length());
            }else{
                CharSequence charSequence = text.subSequence(text.length() - 1, text.length());
                if (!TextUtils.equals(" ", charSequence)) {
                    text.append(" ");
                }
                text.append(appendContent);
                edittext.setText(text);
                edittext.setSelection(text.length());
            }
        }
        item.setAudioLocalPath(url);
        updateMyAudioStyle();

    }

    private String getTempRecordFilePath(){
        if(getContext()==null){
            return "";
        }
        File targetDir = new File(Environment.getExternalStorageDirectory(),
                "Android/data/" + getContext().getApplicationInfo().packageName + "/files/record/klg/temp");
        if (!targetDir.exists()) {
            boolean isCreate=targetDir.mkdirs();
            if(isCreate){
                Log.e("eeee","路径创建成功");
            }
        }
        return targetDir.getPath();
    }

    public String getStuAnswerStr(){
        return item.getStuAnswer();
    }

    public void setStuAnswerStr(String answer){
        item.setStuAnswer(answer);
        if(convertView !=null){
            convertView.findViewById(R.id.edittext).requestLayout();
        }
    }

    public void updateKeyboardShowState(boolean isShow){
//        if(convertView !=null){
//            convertView.findViewById(R.id.rl_bottom).setVisibility(isShow?View.GONE:View.VISIBLE);
//            convertView.findViewById(R.id.bottom_height).setVisibility(isShow?View.GONE:View.VISIBLE);
//        }
    }

    /**
     * 重新上传音频文件
     */
    private void showAudioUploadFailureDialog(){
        ConfirmDialogHelper.showConfirmDialog(getContext(), 2,
                getString(R.string.ev_audio_upload_failure), getString(R.string.ev_upload_retry),
                getString(R.string.ev_cancel), new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        AudioUpLoadEventBean audioUpLoadEventBean=new AudioUpLoadEventBean();
                        audioUpLoadEventBean.setTypeIndex(typeIndex);
                        audioUpLoadEventBean.setQueseIndex(quesIndex);
                        audioUpLoadEventBean.setChildIndex(childIndex);
                        audioUpLoadEventBean.setAudioLocalPath(tempUrl);
                        EventBus.getDefault().post(audioUpLoadEventBean);
                        loadDialog =LoadDialogHelper.showLoadDialog(getContext(), R.string.ev_uploading,false);
                    }
                });
    }

    /**
     * 关闭音频作答
     */
    public void closeAudioAnswer(){
        if(convertView==null){
            return;
        }
        convertView.findViewById(R.id.img_microphone_recording).setEnabled(false);
        Log.e("eee","作文题已关闭");
        if(popupWindow!=null&&popupWindow.isShowing()){
            LancooSpeechRecognitionManager.getInstance(getContext()).stopSpeechRecognition(true);
            popupWindow.dismiss();
        }

    }

    public void adjustFontSize(){
        if(convertView==null){
            return;
        }
        TextView textView = convertView.findViewById(R.id.tv_answer_count);
        TextView textView1 = convertView.findViewById(R.id.tv_ask);
        TextView textView2 = convertView.findViewById(R.id.edittext);
//        TextView textView3 = convertView.findViewById(R.id.tv_clear_answer);
//        TextView textView4 = convertView.findViewById(R.id.tv_my_audio);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView1,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView2,13);
//        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView3,14);
//        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView4,14);
    }

}
